﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class backstage_KeyManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void TempBtn_Click(object sender, EventArgs e)
    {
        KeyDetail kd = GenerateKey();
        string keyId = UpdateKeyTable(kd);
        DownLoad(keyId);
    }
    protected void PermBtn_Click(object sender, EventArgs e)
    {
        KeyDetail kd = GenerateKey(KeyUsageType.Permanent);
        string keyId = UpdateKeyTable(kd);
        DownLoad(keyId);
    }
    protected void TermBtn_Click(object sender, EventArgs e)
    {
        KeyDetail kd = GenerateKey(KeyUsageType.Terminable, int.Parse(Days.Text));
        string keyId = UpdateKeyTable(kd);
        DownLoad(keyId);
    }

    private void DownLoad(string content)
    {
        byte[] buf = Encoding.UTF8.GetBytes(content);
        Response.AddHeader("Content-Disposition", "attachment;filename=key.txt");
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/vnd.ms-excel";

        Response.BinaryWrite(buf);
        Response.Flush();
        Response.Close();
        Response.End();
    }

    private string UpdateKeyTable(KeyDetail kd)
    { 
        PoseidonDBHelper.AdminDB.Insert(kd);
        return kd.KeyId;
    }

    private KeyDetail GenerateKey(KeyUsageType usageType = KeyUsageType.Temporary, int days = 30)
    {
        KeyDetail kd = new KeyDetail();
        kd.IsInUse = false;
        kd.KeyId = Guid.NewGuid().ToString().Replace("-", "");
        kd.UsageTypeInt = (int)usageType;
        switch (usageType)
        {
            case KeyUsageType.Permanent:
                kd.KeyContent = KeyContent.GenerateKey(DateTime.Now, DateTime.MaxValue);
                break;
            case KeyUsageType.Temporary:
                kd.KeyContent = KeyContent.GenerateKey(30);
                break;
            case KeyUsageType.Terminable:
                kd.KeyContent = new KeyContent();
                kd.KeyContent.MaxDays = days;
                break;
        }
        return kd;
    }
}